package com.shycloud.mido.member.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.happy.zebra.admin.api.feign.AdminFeignService;
import com.happy.zebra.admin.api.vo.AssistPermissionVO;
import com.shycloud.common.minio.service.MinioTemplate;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.member.api.dto.MemberV2DTO;
import com.shycloud.mido.member.api.entity.*;
import com.shycloud.mido.member.api.feign.RemoteImService;
import com.shycloud.mido.member.api.util.Constant;
import com.shycloud.mido.member.api.vo.*;
import com.shycloud.mido.member.mapper.MemberActivateMapper;
import com.shycloud.mido.member.mapper.MemberMapper;
import com.shycloud.mido.member.mapper.MemberRoleMapper;
import com.shycloud.mido.member.service.*;
import com.shycloud.mido.music.feign.MusicRemoteService;
import com.shycloud.mido.organ.api.feign.RemoteOrganService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 会员模块 controller
 *
 * @author nianhua.jiang
 * @date 2020/5/21
 */
@RestController
@AllArgsConstructor
@RequestMapping("/member")
@ApiOperation("新会员模块")
@Slf4j
@CrossOrigin(origins = "*")
public class MemberControllerV2 {

	/** 会员业务 service */
	private final MemberServiceV2 memberService;
	/** redis 服务 */
	private final RedisTemplate<String, Object> redisTemplate;
	/** 机构模块 service */
	private final OrgOrganizationService organizationService;
	/** 学生教师 controller */
	private final TeacherStudentController teacherStudent;
	/** 版本信息 service */
	private final AppVersionService appVersionService;
	/** 教师详情 service */
	private final OrgTeacherDetailedService teacherDetailedService;
	/** 学生详情 service */
	private final OrgStudentDetailedService studentDetailedService;
	/** 学生教师关系 service */
	private final OrgTeacherStudentService teacherStudentService;
	/** 用户信息详情 service */
	private final MemberDetailInfoService memberDetailInfoService;
	/** 教师认证 service */
	private final SmMemberTeacherApprovalNewService approvalNewService;
	/** 密码解密 */
	private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();
	/** 七牛云 OSS上传 */
	private final MinioTemplate minioTemplate;
	/** 扫描二维码业务 service */
	private final SmMemberScanCodeService scanCodeService;
	/** 扫描有声图书业务 service */
	private final BaseMusicAuditionCodeService auditionCodeService;
	/** 硬件扫码记录 service */
	private final UdidScanService udidScanService;
	/** 纠错大师 feign 模块 service */
	private final RemoteOrganService masterFeignService;
	/** 教辅权限 feign 模块 service */
	private final AdminFeignService adminFeignService;
	/** 会员充值模块 service */
	private final VipMemberService vipMemberService;
	/** 学生详情 service */
	private final OrgStudentDetailedService studentService;
	/** 微信登录按钮是否显示 */
	private final LockWxService lockWxService;
	/** IM 即时通讯 feign service */
	private final RemoteImService remoteImService;
	/** 教师业务 service */
	private final TeacherService teacherService;
	/** 用户模块 mapper */
	private final MemberMapper memberMapper;
	/** 用户会员模块 service */
	private final MemberRoleMapper memberRoleMapper;
	/** 硬件激活模块 service */
	private final MemberActivateMapper memberActivateMapper;
	/** 注册服务 */
	private final RegisterService registerService;
	/** 上音社用户显示标识 */
	private final SmMemberSyShowFlgService syShowFlgService;
	/** 曲目模块 feign */
	private final MusicRemoteService musicRemoteService;
	/** 视频页面 service */
	private final SmMemberVideoPageService videoPageService;
	/** 视频页面观看记录 service */
	private final SmMemberVideoWatchDataService watchDataService;
	/** 上音设旧码扫码记录业务 service */
	private final SmMemberScanSyOldCodeLogService scanSyOldCodeLogService;
	/** IOS client 配置业务 service */
	private final AppleClientService appleClientService;
	/** 教师身份 */
	private static final String TEACHER = "1";
	/** 学生身份 */
	private static final String STUDENT = "0";

	/**
	 * APP端 注册会员
	 *
	 * @param map 会员注册信息
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/27 10:50
	 */
	@PostMapping("/register")
	@ApiOperation(value = "mobile-注册会员")
	public R<Boolean> mobileRegister(@RequestBody Map<String, String> map) {
		return new R<>(registerService.appRegister(map));
	}

	/**
	 * 移动端更新用户信息
	 *
	 * @param map 更新用户数据体
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/28 14:01
	 */
	@ApiOperation("移动端更新用户信息")
	@PostMapping("updateMobileUser")
	public R<Boolean> updateMobileUser(@RequestBody Map<String, String> map) {
		return new R<>(memberService.updateMobileUser(map));
	}

	/**
	 * 更新会员个推会员标识
	 *
	 * @param memberId 会员ID
	 * @param clientId 个推会员标识
	 * @return com.shycloud.mido.common.core.util.R
	 */
	@PostMapping("/updClientId")
	public R<Boolean> updClientId(String memberId, String clientId) {
		return memberService.updClientId(memberId, clientId);
	}

	/**
	 * 上传头像
	 *
	 * @param headerImg 图片URL
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/4/30 9:26
	 */
	@PostMapping("uploadHeader")
	@ApiOperation(value = "上传头像")
	public R<Object> uploadImage(@RequestParam("headerImg") MultipartFile headerImg) {

		// 提取后缀
		// 提取图片名称
		String fileName = headerImg.getOriginalFilename().replace(" ", "");
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

		String uuid = UUID.randomUUID().toString();

		// 提取图片名称
		String imgName = uuid.replace("-", "") + "." + suffix;
		// 初始化map结果集
		Map<String, String> resultMap = new HashMap<>(4);
		// 名称
		resultMap.put("name", imgName);
		try {
			// 上传操作
			resultMap.put("url", minioTemplate.uploadFile(headerImg.getInputStream(), imgName));
		} catch (Exception e) {
			return R.builder().code(CommonConstants.FAIL).msg(e.getLocalizedMessage()).build();
		}
		return R.builder().data(resultMap).build();
	}

	/**
	 * 登录获取用户详情
	 *
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/23 10:31
	 */
	@GetMapping("getUserDetail")
	@ApiOperation("登录获取用户详情")
	public R<Object> getUserDetail() {

		// 创建 Map 结果集
		Map<String, Object> resultMap = MapUtil.newHashMap();

		// 获取登录用户的memberId
		String memberId = SecurityUtils.getMember().getId();

		// phone
		String phone = SecurityUtils.getMember().getPhone();

		// 获取用户的默认机构
		List<OrgOrganization> orgList = organizationService
				.list(new QueryWrapper<OrgOrganization>().eq("phone", phone)
						// 状态启用（0）/禁用（1）
						.and(x -> x.eq("status", "0")));

		resultMap.put("orgDetail", orgList);

		// 获取用户信息
		MemberDetailForLoginVO loginVO = memberService.getUserDetail(memberId);
		resultMap.put("memberDetail", loginVO);

		// 返回结果
		return new R<>(resultMap);
	}

	/**
	 * 分页查询会员信息
	 *
	 * @param memberDTO 查询会员信息的条件
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/22 16:54
	 */
	@PostMapping("page")
	@ApiOperation("分页获取会员信息")
	public R<IPage<MemberV2VO>> page(@RequestBody MemberV2DTO memberDTO) {
		// 分页参数
		Page<MemberV2VO> page = new Page<>(memberDTO.getCurrent(), memberDTO.getSize());
		// erp用户权限，显示所有用户的信息
		return new R<>(memberService.getMemberVosPageV2(page, memberDTO));
	}

	/**
	 * 新建会员
	 *
	 * @param memberDTO 会员信息
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/22 16:54
	 */
	@PostMapping("addMember")
	@ApiOperation(value = "新建会员", notes = "参数为：province，city,identity（0-学生 1-教师），phone，showname，studioName，registerFrom = 98 姜杰团队注册,tag 顶部文案")
	public R<String> addMember(@RequestBody MemberV2DTO memberDTO) {
		return new R<>(registerService.register(memberDTO));
	}

	/**
	 * 更新会员信息
	 *
	 * @param memberDTO 更新会员信息的数据
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/25 15:32
	 */
	@PostMapping("updateMember")
	@ApiOperation("更新会员信息")
	public R<Boolean> updateMember(@RequestBody MemberV2DTO memberDTO) {
		return memberService.updateMember(memberDTO);
	}

	/**
	 * 获取用户详情
	 *
	 * @param id 用户ID
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/26 9:52
	 */
	@GetMapping("getMemberDetail")
	@ApiOperation("获取用户详情")
	public R<Map<String, Object>> getMemberDetail(String id) {

		// 初始化结果集
		Map<String, Object> resultMap = MapUtil.newHashMap();
		// 归属信息
		resultMap.put("relationship", memberService.getRelationship(id));
		// 用户详细信息
		resultMap.put("memberDetail", memberService.getMemberDetail(id));

		return new R<>(resultMap);

	}

	/**
	 * 移除所属关系
	 *
	 * @param studentId 学生ID
	 * @param teacherId 教师ID
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/26 11:18
	 */
	@GetMapping("removeRelationship")
	@ApiOperation("移除所属关系")
	public R<Boolean> removeRelationship(String studentId, String teacherId) {
		if (memberService.removeRelationship(studentId, teacherId) == 1) {
			return new R<>(CommonConstants.SUCCESS, "移除成功", true);
		} else {
			return new R<>(CommonConstants.FAIL, "移除失败", false);
		}
	}

	/**
	 * 分页获取充值会员信息
	 *
	 * @param current 页数
	 * @param size    每页显示条数
	 * @param phone   电话号/账号/用户名
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/29 13:25
	 */
	@GetMapping("getVipMember")
	@ApiOperation("分页获取充值会员信息")
	public R<IPage<MemberV2VO>> getVipMember(Integer current, Integer size, String phone, String identity,
											 Integer dayLeft, String startDate, String endDate) {

		// 分页参数
		Page<MemberV2VO> page = new Page<>(current, size);
		IPage<MemberV2VO> vipMember = memberService.getVipMember(page, phone, identity, dayLeft, startDate, endDate);
		return new R<>(vipMember);

	}

	/**
	 * 会员开通
	 *
	 * @param request 请求数据
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/2 17:20
	 */
	@PostMapping("addVipMember")
	@ApiOperation("会员开通")
	public R<Object> addVipMember(@RequestBody Map<String, Object> request) {

		if (request == null) {
			return new R<>(CommonConstants.FAIL, "请求参数错误", false);
		}

		// 电话号码
		String phone = (String) request.get("phone");
		// 开通时长
		Integer useTime = (Integer) request.get("useTime");

		return new R<>(memberService.addVipMember(phone, useTime));
	}

	/**
	 * 根据手机号查询用户信息
	 *
	 * @param phone 手机号
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/27 13:32
	 */
	@GetMapping("getMemberByPhone")
	@ApiOperation("根据手机号查询用户信息")
	public R<Object> getMemberByPhone(String phone) {

		if (phone == null || "".equals(phone)) {
			return new R<>(CommonConstants.FAIL, "请输入手机号", false);
		}

		if (memberService.getMemberByPhone(phone) != null) {
			return new R<>(memberService.getMemberByPhone(phone));
		} else {
			return new R<>(CommonConstants.FAIL, "查询用户不存在", false);
		}

	}

	/**
	 * 通过用户名字查询用户信息
	 *
	 * @param username 用户名
	 * @return com.shycloud.mido.common.core.util.R
	 */
	@GetMapping("getMemberByUsername")
	@ApiOperation("根据手机号查询用户信息")
	public R<Object> getMemberByUsername(String username) {

		if (username == null || "".equals(username)) {
			return new R<>(CommonConstants.FAIL, "请输入查询信息", false);
		}
		LambdaQueryWrapper<Member> query = Wrappers.<Member>lambdaQuery()
				.eq(Member::getDelFlag, Constant.DEL_FLAG)
				.eq(Member::getUsername, username);
		Member member = memberService.getOne(query);
		if (member != null) {
			return new R<>(member);
		} else {
			return new R<>(CommonConstants.FAIL, "查询用户不存在", false);
		}

	}

	/**
	 * 根据用户账号查询用户所在机构
	 *
	 * @param username 用户名
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/8 14:38
	 */
	@GetMapping("getOrgListByUsername")
	@ApiOperation("根据用户账号查询用户所在机构")
	public R<List<Map<String, String>>> getOrgListByUsername(String username) {
		return new R<>(memberService.getOrgListByUsername(username));
	}

	@GetMapping("/getCaptcha")
	public R<String> getCaptcha() {
		String captcha;
		Object codeObj = redisTemplate.opsForValue().get("superCaptcha");
		if (codeObj == null) {
			String code = RandomUtil.randomNumbers(6);
			redisTemplate.opsForValue().set("superCaptcha", code, 86400, TimeUnit.SECONDS);
			captcha = code;
		} else {
			captcha = codeObj.toString();
		}
		return new R<>(captcha);
	}

	@GetMapping("/refreshCaptcha")
	public R<String> refreshCaptcha() {
		String captcha;
		String code = RandomUtil.randomNumbers(6);
		redisTemplate.opsForValue().set("superCaptcha", code, 86400, TimeUnit.SECONDS);
		captcha = code;

		return new R<>(captcha);
	}

	@GetMapping("/getPWD")
	public R<String> getPWD() {
		String PWD;
		Object codeObj = redisTemplate.opsForValue().get("superPWD");
		if (codeObj == null) {
			String code = RandomUtil.randomNumbers(6);
			redisTemplate.opsForValue().set("superPWD", code, 86400, TimeUnit.SECONDS);
			PWD = code;
		} else {
			PWD = codeObj.toString();
		}
		return new R<>(PWD);
	}

	@GetMapping("/refreshPWD")
	public R<String> refreshPWD() {
		String PWD;
		String code = RandomUtil.randomNumbers(6);
		redisTemplate.opsForValue().set("superPWD", code, 86400, TimeUnit.SECONDS);
		PWD = code;

		return new R<>(PWD);
	}

	@ApiOperation("返回首页请求数据")
	@GetMapping("homePage")
	public R<Object> homePage() {
		HomePageVO homePage = new HomePageVO();
		// 用户ID
		String memberId = SecurityUtils.getMember().getId();

		// 用户信息
		Member member = memberService.getById(memberId);
		if (member == null) {
			return new R<>(CommonConstants.FAIL, "用户信息获取失败", false);
		}

		//==================== 2020/11/05 ADD BY NIANHUA.JIANG START=====================//
		if (StringUtils.isEmpty(member.getAccount())) {
			String account = memberService.getAccount();
			member.setAccount(account);
		}
		//==================== 2020/11/05 ADD BY NIANHUA.JIANG E N D=====================//

		//==================== 2021/10/14 add by nianhua.jiang START=====================//
		//更新活跃用户情况
		member.setLoginTime(LocalDateTime.now());
		memberService.updateById(member);
		//==================== 2021/10/14 add by nianhua.jiang E N D=====================//

		// 用户详情
		MemberDetailInfo memberDetailInfo = memberDetailInfoService
				.getOne(new QueryWrapper<MemberDetailInfo>().eq("member_id", memberId));

		if (memberDetailInfo != null) {
			// 生日
			homePage.setBirthday(memberDetailInfo.getBirthday());
			// 性别
			homePage.setSex(memberDetailInfo.getSex());
			//琴龄
			homePage.setPlayYears(memberDetailInfo.getPlayYears());
			//目标
			homePage.setPlayTarget(memberDetailInfo.getPlayTarget());
		}

		// 用户ID
		homePage.setUser_id(memberId);
		// 电话号码
		homePage.setPhone(member.getPhone());
		// 昵称
		homePage.setShowName(member.getShowname());
		// 用户名
		homePage.setUsername(member.getUsername());

		//=============================== 上音社用户标识 2021-11-11 nianhua.jiang ADD ====================================//
		//检索sy表
		int count = syShowFlgService.count(new QueryWrapper<SmMemberSyShowFlg>().eq("member_id", memberId));
		if (count > 0) {
			homePage.setSyShow("0");
		} else {
			homePage.setSyShow("1");
		}
		//=============================== 上音社用户标识 2021-11-11 nianhua.jiang ADD ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//

		//=============================== 教师审核状态 0-教师 1-学生 2-教师审核中 2020/11/12 nianhua.jiang ADD =============//
		homePage.setIsTeacher("0");
		//查询 teacher 表看是否有数据
		List<OrgTeacherDetailed> orgTeacherDetaileds = teacherDetailedService
				.list(new QueryWrapper<OrgTeacherDetailed>()
						.eq("member_id", memberId)
						.and(x -> x.eq("del_flag", "0")));

		if (orgTeacherDetaileds.size() > 0) {
			homePage.setIsTeacher("1");
		} else {
			//查询教师申请表，取出其状态
			SmMemberTeacherApprovalNew smMemberTeacherApprovalNew = approvalNewService
					.getOne(new QueryWrapper<SmMemberTeacherApprovalNew>()
							.eq(SmMemberTeacherApprovalNew.COL_MEMBER_ID, memberId));
			if (smMemberTeacherApprovalNew != null && StringUtils
					.isNotBlank(smMemberTeacherApprovalNew.getStatus())) {
				//状态 0-审核中
				if ("0".equals(smMemberTeacherApprovalNew.getStatus())) {
					homePage.setIsTeacher("2");
				}
				//状态 2-已驳回
				if ("2".equals(smMemberTeacherApprovalNew.getStatus())) {
					homePage.setIsTeacher("0");
				}
			}
		}
		//=============================== 教师审核状态 0-教师 1-学生 2-教师审核中 2020/11/12 nianhua.jiang ADD =============//

		// 头像
		homePage.setHead(member.getAvatar());
		//剩余虚拟币
		homePage.setGold(member.getGold());
		//是否是会员
		VipMemberVO vipMemberVO = vipMemberService.getVipMemberDetail(memberId);
		homePage.setIsVip("1".

				equals(vipMemberVO.getIsVipString()));
		//用户mp3下载次数
		homePage.setDownloadMp3Count(member.getDownloadMp3Count());
		//VIP用户每月下载次数
		homePage.setDownloadTotalMp3Count(300);
		//VIP到期时间
		List<MemberRole> memberRoles = memberRoleMapper.selectList(new QueryWrapper<MemberRole>().eq("member_id", memberId));

		if (memberRoles.size() > 0) {
			homePage.setVipOverDateTime(
					String.valueOf(memberRoles.get(0).getEndTime().toInstant(ZoneOffset.of("+8")).toEpochMilli()));
		}

		// 我的作业提醒
		// 获取学生ID
		String studentId = teacherStudent.getStudentId(memberId);
		// 检索作业主表，看是否有新的作业提醒
		List<String> ding = memberService.getDing(studentId);
		homePage.setRemind(ding.contains("1"));

		// 教师身份
		if (TEACHER.equals(member.getIsTeacher())) {

			// 查询教师表，获取默认机构ID
			List<OrgTeacherDetailed> teacherDetaileds = teacherDetailedService
					.list(new QueryWrapper<OrgTeacherDetailed>()
							.eq(OrgTeacherDetailed.COL_MEMBER_ID, member.getId())
							.and(x -> x.eq(OrgTeacherDetailed.COL_DEL_FLAG,
									CommonConstants.STATUS_NORMAL))
							.orderByAsc(OrgTeacherDetailed.COL_CREATE_TIME));

			if (teacherDetaileds.size() == 0) {
				return new R<>(CommonConstants.FAIL, "教师信息获取失败", false);
			} else {
				// 获取机构信息
				OrgOrganization org = organizationService
						.getById(teacherDetaileds.get(0).getOrgId());
				// 机构ID
				homePage.setOrg_id(org.getId());
				// 机构名
				homePage.setOrg_name(org.getName());
				// 机构欢迎语
				homePage.setWelcomeWord(org.getTag());
				// 教师ID
				homePage.setTeacherId(teacherDetaileds.get(0).getId());
				// 教师姓名
				homePage.setTeacherName(teacherDetaileds.get(0).getName());

				homePage.setTeacherMemberShowName(member.getShowname());
				//教师头像
				homePage.setTeacherHead(homePage.getHead());
				//教师 imId
				homePage.setTeacherImId(member.getImUserId());
				List<OrgTeacherStudent> teacherStudent = teacherStudentService
						.list(new QueryWrapper<OrgTeacherStudent>()
								.eq("teacher_id", teacherDetaileds.get(0).getId()));

				homePage.setHasStudents(teacherStudent.size() > 0 ? "1" : "0");

			}
		}

		// 学生身份
		if (STUDENT.equals(member.getIsTeacher())) {
			// 查询教师表，获取默认机构ID
			List<OrgStudentDetailed> studentDetaileds = studentDetailedService
					.list(new QueryWrapper<OrgStudentDetailed>()
							.eq(OrgStudentDetailed.COL_MEMBER_ID, member.getId())
							.and(x -> x.eq(OrgStudentDetailed.COL_DEL_FLAG,
									CommonConstants.STATUS_NORMAL))
							.orderByAsc(OrgStudentDetailed.COL_CREATE_TIME));

			// 学生ID
			if (studentDetaileds.size() > 0) {
				homePage.setStudentId(studentDetaileds.get(0).getId());
			}

			if (studentDetaileds.size() > 0 && studentDetaileds.get(0).getOrgId() != 0) {
				// 获取机构信息
				OrgOrganization org = organizationService
						.getById(studentDetaileds.get(0).getOrgId());
				// 机构ID
				homePage.setOrg_id(org.getId());
				// 机构名
				homePage.setOrg_name(org.getName());
				// 机构欢迎语
				homePage.setWelcomeWord(org.getTag());

				// 教师ID
				try {
					OrgTeacherStudent teacherStudent = teacherStudentService
							.getOne(new QueryWrapper<OrgTeacherStudent>()
									.eq("student_id", studentDetaileds.get(0).getId()));

					homePage.setTeacherId(
							teacherStudent == null ? null : teacherStudent.getTeacherId());

					//获取教师姓名/头像
					MyTeacherVO myTeacher = teacherService.getMyTeacher(studentDetaileds.get(0).getId());
					homePage.setTeacherName(myTeacher.getName());
					homePage.setTeacherHead(myTeacher.getHeader());
					homePage.setTeacherImId(myTeacher.getImId());
					homePage.setTeacherMemberShowName(myTeacher.getMemberShowName());
				} catch (Exception e) {
					e.printStackTrace();
					return new R<>(CommonConstants.FAIL, "教师与学生数据存在问题，请联系客服处理~~", false);
				}

			} else {
				// 机构ID
				homePage.setOrg_id(0);
				// 机构名
				homePage.setOrg_name("暂无机构");
				// 机构欢迎语
				homePage.setWelcomeWord("HELLO，欢迎来到快乐斑马!");
			}
		}
		if (homePage.getWelcomeWord() == null) {
			homePage.setWelcomeWord("HELLO，欢迎来到快乐斑马!");
		}

		//获取版本信息
		AppVersion appVersion = appVersionService.getOne(new QueryWrapper<AppVersion>().eq(AppVersion.COL_STATUS, "1"));
		//版本信息
		homePage.setAppVersion(appVersion);
		//是否显示总榜
		homePage.setShowTotalRank(appVersion.getShowTotalRank());
		//查询教辅权限表，看此教师（学生）是否有教辅权限
		String teacherId = homePage.getTeacherId();

		//查询用户是否有教辅权限
		R<AssistPermissionVO> resultAssist = adminFeignService.checkAssistPermission(teacherId);
		AssistPermissionVO resultMapAssist = resultAssist.getData();
		homePage.setIsAssistPermission(resultMapAssist.getStatus());
		homePage.setAssistType(resultMapAssist.getType());
		//是否开通纠错大师
		R<Map<String, Object>> result = masterFeignService.checkMemberMaster(memberId);
		//返回数据结果集
		Map<String, Object> resultMap = result.getData();
		homePage.setIsMaster((Integer) resultMap.get("status") == 1);
		homePage.setMiniStatus(member.getMiniStatus());
		//订阅周报
		homePage.setSubscribe(member.getSubscribe());
		//是否已经订阅【周期扣款】
		homePage.setIsAgreementSign(member.getIsAgreementSign());
		//注册来源
		homePage.setRegisterFrom(member.getRegisterFrom());

		//规定日期后的用户需要加标识 暂定 2022-01-31
		List<MemberActivateEntity> memberActivateEntities = memberActivateMapper
				.selectList(new QueryWrapper<MemberActivateEntity>().eq("member_id", memberId)
						.gt("create_time", "2022-01-31"));

		if (memberActivateEntities.stream().anyMatch(x -> x.getDuration() == 0)) {
			homePage.setIsForever("1");
		} else {
			homePage.setIsForever("0");
		}

		return new R<>(homePage);
	}

	/**
	 * 返回首页请求数据
	 *
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/7/5 14:40
	 */
	@ApiOperation("返回首页请求数据")
	@GetMapping("homePageV2")
	public R<Object> homePageV2() {

		HomePageVO homePage = new HomePageVO();
		// 用户ID
		String memberId = SecurityUtils.getMember().getId();

		// 用户信息
		Member member = memberService.getById(memberId);
		if (member == null) {
			return new R<>(CommonConstants.FAIL, "用户信息获取失败", false);
		}

		//==================== 2020/11/05 ADD BY NIANHUA.JIANG START=====================//
		if (StringUtils.isEmpty(member.getAccount())) {
			String account = memberService.getAccount();
			member.setAccount(account);
		}
		//==================== 2020/11/05 ADD BY NIANHUA.JIANG E N D=====================//

		//==================== 2021/10/14 add by nianhua.jiang START=====================//
		//更新活跃用户情况
		member.setLoginTime(LocalDateTime.now());
		memberService.updateById(member);
		//==================== 2021/10/14 add by nianhua.jiang E N D=====================//

		// 用户详情
		MemberDetailInfo memberDetailInfo = memberDetailInfoService
				.getOne(new QueryWrapper<MemberDetailInfo>().eq("member_id", memberId));

		if (memberDetailInfo != null) {
			// 生日
			homePage.setBirthday(memberDetailInfo.getBirthday());
			// 性别
			homePage.setSex(memberDetailInfo.getSex());
			//琴龄
			homePage.setPlayYears(memberDetailInfo.getPlayYears());
			//目标
			homePage.setPlayTarget(memberDetailInfo.getPlayTarget());
		}

		// 用户ID
		homePage.setUser_id(memberId);
		// 电话号码
		homePage.setPhone(member.getPhone());
		// 昵称
		homePage.setShowName(member.getShowname());
		// 用户名
		homePage.setUsername(member.getUsername());

		//=============================== 上音社用户标识 2021-11-11 nianhua.jiang ADD ====================================//
		//检索sy表
		int count = syShowFlgService.count(new QueryWrapper<SmMemberSyShowFlg>().eq("member_id", memberId));
		if (count > 0) {
			homePage.setSyShow("0");
		} else {
			homePage.setSyShow("1");
		}
		//=============================== 上音社用户标识 2021-11-11 nianhua.jiang ADD ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//

		//=============================== 教师审核状态 0-教师 1-学生 2-教师审核中 2020/11/12 nianhua.jiang ADD =============//
		homePage.setIsTeacher("0");
		//查询 teacher 表看是否有数据
		List<OrgTeacherDetailed> orgTeacherDetaileds = teacherDetailedService
				.list(new QueryWrapper<OrgTeacherDetailed>()
						.eq("member_id", memberId)
						.and(x -> x.eq("del_flag", "0")));

		if (orgTeacherDetaileds.size() > 0) {
			homePage.setIsTeacher("1");
		} else {
			//查询教师申请表，取出其状态
			SmMemberTeacherApprovalNew smMemberTeacherApprovalNew = approvalNewService
					.getOne(new QueryWrapper<SmMemberTeacherApprovalNew>()
							.eq(SmMemberTeacherApprovalNew.COL_MEMBER_ID, memberId));
			if (smMemberTeacherApprovalNew != null && StringUtils
					.isNotBlank(smMemberTeacherApprovalNew.getStatus())) {
				//状态 0-审核中
				if ("0".equals(smMemberTeacherApprovalNew.getStatus())) {
					homePage.setIsTeacher("2");
				}
				//状态 2-已驳回
				if ("2".equals(smMemberTeacherApprovalNew.getStatus())) {
					homePage.setIsTeacher("0");
				}
			}
		}
		//=============================== 教师审核状态 0-教师 1-学生 2-教师审核中 2020/11/12 nianhua.jiang ADD =============//

		// 头像
		homePage.setHead(member.getAvatar());
		//剩余虚拟币
		homePage.setGold(member.getGold());
		//是否是会员
		VipMemberVO vipMemberVO = vipMemberService.getVipMemberDetail(memberId);
		homePage.setIsVip("1".equals(vipMemberVO.getIsVipString()));
		//用户mp3下载次数
		homePage.setDownloadMp3Count(member.getDownloadMp3Count());
		//VIP用户每月下载次数
		homePage.setDownloadTotalMp3Count(300);
		//VIP到期时间
		List<MemberRole> memberRoles = memberRoleMapper.selectList(new QueryWrapper<MemberRole>().eq("member_id", memberId));

		if (memberRoles.size() > 0) {
			homePage.setVipOverDateTime(
					String.valueOf(memberRoles.get(0).getEndTime().toInstant(ZoneOffset.of("+8")).toEpochMilli()));
		}

		// 我的作业提醒
		// 获取学生ID
		String studentId = teacherStudent.getStudentId(memberId);
		// 检索作业主表，看是否有新的作业提醒
		List<String> ding = memberService.getDing(studentId);
		homePage.setRemind(ding.contains("1"));

		// 教师身份
		if (TEACHER.equals(member.getIsTeacher())) {

			// 查询教师表，获取默认机构ID
			List<OrgTeacherDetailed> teacherDetaileds = teacherDetailedService
					.list(new QueryWrapper<OrgTeacherDetailed>()
							.eq(OrgTeacherDetailed.COL_MEMBER_ID, member.getId())
							.and(x -> x.eq(OrgTeacherDetailed.COL_DEL_FLAG,
									CommonConstants.STATUS_NORMAL))
							.orderByAsc(OrgTeacherDetailed.COL_CREATE_TIME));

			if (teacherDetaileds.size() == 0) {
				return new R<>(CommonConstants.FAIL, "教师信息获取失败", false);
			} else {
				// 获取机构信息
				OrgOrganization org = organizationService
						.getById(teacherDetaileds.get(0).getOrgId());
				// 机构ID
				homePage.setOrg_id(org.getId());
				// 机构名
				homePage.setOrg_name(org.getName());
				// 机构欢迎语
				homePage.setWelcomeWord(org.getTag());
				// 教师ID
				homePage.setTeacherId(teacherDetaileds.get(0).getId());
				// 教师姓名
				homePage.setTeacherName(teacherDetaileds.get(0).getName());

				homePage.setTeacherMemberShowName(member.getShowname());
				//教师头像
				homePage.setTeacherHead(homePage.getHead());
				//教师 imId
				homePage.setTeacherImId(member.getImUserId());
				List<OrgTeacherStudent> teacherStudent = teacherStudentService
						.list(new QueryWrapper<OrgTeacherStudent>()
								.eq("teacher_id", teacherDetaileds.get(0).getId()));

				homePage.setHasStudents(teacherStudent.size() > 0 ? "1" : "0");

			}
		}

		// 学生身份
		if (STUDENT.equals(member.getIsTeacher())) {
			// 查询教师表，获取默认机构ID
			List<OrgStudentDetailed> studentDetaileds = studentDetailedService
					.list(new QueryWrapper<OrgStudentDetailed>()
							.eq(OrgStudentDetailed.COL_MEMBER_ID, member.getId())
							.and(x -> x.eq(OrgStudentDetailed.COL_DEL_FLAG,
									CommonConstants.STATUS_NORMAL))
							.orderByAsc(OrgStudentDetailed.COL_CREATE_TIME));

			// 学生ID
			if (studentDetaileds.size() > 0) {
				homePage.setStudentId(studentDetaileds.get(0).getId());
			}

			if (studentDetaileds.size() > 0 && studentDetaileds.get(0).getOrgId() != 0) {
				// 获取机构信息
				OrgOrganization org = organizationService
						.getById(studentDetaileds.get(0).getOrgId());
				// 机构ID
				homePage.setOrg_id(org.getId());
				// 机构名
				homePage.setOrg_name(org.getName());
				// 机构欢迎语
				homePage.setWelcomeWord(org.getTag());

				// 教师ID
				try {
					OrgTeacherStudent teacherStudent = teacherStudentService
							.getOne(new QueryWrapper<OrgTeacherStudent>()
									.eq("student_id", studentDetaileds.get(0).getId()));

					homePage.setTeacherId(
							teacherStudent == null ? null : teacherStudent.getTeacherId());

					//获取教师姓名/头像
					MyTeacherVO myTeacher = teacherService.getMyTeacher(studentDetaileds.get(0).getId());
					homePage.setTeacherName(myTeacher.getName());
					homePage.setTeacherHead(myTeacher.getHeader());
					homePage.setTeacherImId(myTeacher.getImId());
					homePage.setTeacherMemberShowName(myTeacher.getMemberShowName());
				} catch (Exception e) {
					e.printStackTrace();
					return new R<>(CommonConstants.FAIL, "教师与学生数据存在问题，请联系客服处理~~", false);
				}

			} else {
				// 机构ID
				homePage.setOrg_id(0);
				// 机构名
				homePage.setOrg_name("暂无机构");
				// 机构欢迎语
				homePage.setWelcomeWord("HELLO，欢迎来到快乐斑马!");
			}
		}
		if (homePage.getWelcomeWord() == null) {
			homePage.setWelcomeWord("HELLO，欢迎来到快乐斑马!");
		}

		//获取版本信息
		AppVersion appVersion = appVersionService.getOne(new QueryWrapper<AppVersion>().eq(AppVersion.COL_STATUS, "1"));
		//版本信息
		homePage.setAppVersion(appVersion);
		//是否显示总榜
		homePage.setShowTotalRank(appVersion.getShowTotalRank());
		//查询教辅权限表，看此教师（学生）是否有教辅权限
		String teacherId = homePage.getTeacherId();

		//查询用户是否有教辅权限
		R<AssistPermissionVO> resultAssist = adminFeignService.checkAssistPermission(teacherId);
		AssistPermissionVO resultMapAssist = resultAssist.getData();
		homePage.setIsAssistPermission(resultMapAssist.getStatus());
		homePage.setAssistType(resultMapAssist.getType());
		//是否开通纠错大师
		R<Map<String, Object>> result = masterFeignService.checkMemberMaster(memberId);
		//返回数据结果集
		Map<String, Object> resultMap = result.getData();
		homePage.setIsMaster((Integer) resultMap.get("status") == 1);
		homePage.setMiniStatus(member.getMiniStatus());
		//订阅周报
		homePage.setSubscribe(member.getSubscribe());
		//是否已经订阅【周期扣款】
		homePage.setIsAgreementSign(member.getIsAgreementSign());
		//注册来源
		homePage.setRegisterFrom(member.getRegisterFrom());

		//规定日期后的用户需要加标识 暂定 2022-01-31
		List<MemberActivateEntity> memberActivateEntities = memberActivateMapper
				.selectList(new QueryWrapper<MemberActivateEntity>().eq("member_id", memberId)
						.gt("create_time", "2022-01-31"));

		if (memberActivateEntities.stream().anyMatch(x -> x.getDuration() == 0)) {
			homePage.setIsForever("1");
		} else {
			homePage.setIsForever("0");
		}

		// 2022-05-05 新业务需求：
		// 1. 业务背景：取消硬件码业务，硬件条上不贴硬件码了，也不用手动在APP内激活，改用客服手动激活，只要缴纳 500 押金客服就手动激活 12 个月。
		// 2. 更改内容：现将 2022-05-05 23:00:00 之后的激活用户全部限制使用，也就是说 udid = actvCode 的所有数据限制使用
		if ("0".equals(homePage.getIsForever())) {
			long newCount = memberActivateMapper
					.selectCount(new QueryWrapper<MemberActivateEntity>()
							.eq("member_id", memberId)
							.eq("special_type", "1")
							.eq("status", "1")
							.gt("create_time", "2022-05-05 22:20:00"));
			if (newCount > 0) {
				homePage.setIsForever("1");
			}
		}

		return new R<>(homePage);
	}

	@GetMapping("/serveInfo")
	@ApiOperation("服务信息")
	public R<Object> serveInfo(String memberId) {

		Map<String, Object> result = new HashMap<>();
		MemberRole memberRole = memberRoleMapper.selectById(memberId);

		//根据 memberId 查询用户激活信息
		List<MemberActivateEntity> memberActivateEntityList = memberActivateMapper
				.selectList(new QueryWrapper<MemberActivateEntity>()
						.eq("member_id", memberId)
						.orderByDesc("start_time"));

		OrgOrganization org = new OrgOrganization();
		Member member = memberService.getById(memberId);
		QueryWrapper<MemberDetailInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("member_id", memberId);
		MemberDetailInfo memberDetail = memberDetailInfoService.getOne(queryWrapper);
		if ("1".equals(member.getIsTeacher())) {
			//如果是老师 去教师表查询机构信息
			QueryWrapper<OrgTeacherDetailed> teacherWrapper = new QueryWrapper<>();
			teacherWrapper.eq("member_id", memberId);
			OrgTeacherDetailed teacher = teacherDetailedService.getOne(teacherWrapper);
			org = organizationService.getById(teacher.getOrgId());
		} else {
			//如果是学生 去学生表查询机构信息
			QueryWrapper<OrgStudentDetailed> studentWrapper = new QueryWrapper<>();
			studentWrapper.eq("member_id", memberId);
			OrgStudentDetailed student = studentDetailedService.getOne(studentWrapper);
			if (student != null && student.getOrgId() != 0) {
				org = organizationService.getById(student.getOrgId());
			}
		}

		// 赠送会员时长
		result.put("giftMembership", member.getGiftMembership());

		result.put("account", member.getUsername());
		result.put("name", member.getShowname());
		result.put("role", member.getIsTeacher());
		if (null != memberDetail) {
			result.put("sex", memberDetail.getSex());
			if (null != memberDetail.getBirthday()) {
				result.put("age", yearDateDiff(memberDetail.getBirthday()));
			} else {
				result.put("age", 0);
			}
		} else {
			result.put("sex", 0);
			result.put("age", 0);
		}
		result.put("regTime", member.getRegTime());
		if (null != memberRole) {
			result.put("isVip", true);
			result.put("vipDuration",
					Duration.between(memberRole.getStartTime(), memberRole.getEndTime()).toDays());
			result.put("vipEndTime", memberRole.getEndTime());
		} else {
			result.put("isVip", false);
			result.put("vipEndTime", "暂无");
			result.put("vipDuration", "暂无");
		}

		if (memberActivateEntityList.size() > 0) {

			result.put("isHardwareVip", true);
			int duration = 0;

			//循环取到期时间最后的
			LocalDateTime endTime = memberActivateEntityList.get(0).getStartTime()
					.plusDays(memberActivateEntityList.get(0).getDuration());

			for (MemberActivateEntity memberActivateEntity : memberActivateEntityList) {
				//如果有一条到期时间为永久，直接返回
				if (memberActivateEntity.getDuration() == 0) {
					result.put("hardwareVipDuration", "永久");
					break;
				} else {
					duration += memberActivateEntity.getDuration();
					//循环取到期时间最后的
					if (endTime.isBefore(memberActivateEntity.getStartTime().plusDays(memberActivateEntity.getDuration()))) {
						endTime = memberActivateEntity.getStartTime().plusDays(memberActivateEntity.getDuration());
					}
				}
			}

			result.put("hardwareVipEndTime", endTime);

			if (!result.containsKey("hardwareVipDuration")) {
				result.put("hardwareVipDuration", duration);
			}

			result.put("udid", memberActivateEntityList.get(0).getUdid());

		} else {
			result.put("isHardwareVip", false);
			result.put("hardwareVipEndTime", "暂无");
			result.put("hardwareVipDuration", "暂无");
			result.put("udid", "暂无");
		}
		result.put("usedPrint", member.getPrintAmountUsed());
		result.put("surplusPrint", member.getPrintAmountBuy() + member.getPrintAmountGive());
		List<OrgOrganization> list = new ArrayList<>();
		if (null != org.getId()) {
			list.add(org);
		}
		result.put("organization", list);

		return new R<>(result);
	}

	@GetMapping("/resetPWD")
	@ApiOperation("重置密码")
	public R<Integer> resetPWD(String memberId) {
		Member member = memberMapper.selectById(memberId);
		member.setPassword(ENCODER.encode("123456"));
		return new R<>(memberMapper.updateById(member));
	}

	@GetMapping("/updatePWD")
	@ApiOperation("重置密码")
	public R<Integer> updatePWD(String memberId, String pwd) {
		Member member = memberMapper.selectById(memberId);
		member.setPassword(ENCODER.encode(pwd));
		return new R<>(memberMapper.updateById(member));
	}

	@GetMapping("/delayVip")
	@ApiOperation("开通延期(会员)")
	public R<Boolean> delayVip(String memberId, Integer duration) {
		if (duration == 360) {
			duration = 365;
		}
		return new R<>(memberService.addVipMemberByMemberId(memberId, duration));
	}

	@GetMapping("/assignVip")
	@ApiOperation("主账号分配会员")
	public R<Boolean> assignVip(String memberId, Integer number) {

		return new R<>(memberService.assignVip(memberId, number));
	}

	@GetMapping("/delayHardwareVip")
	@ApiOperation("开通延期(硬件)")
	public R<Boolean> delayHardwareVip() {
		return new R<>();
	}

	@GetMapping("/givePrint")
	@ApiOperation("赠送打印卷")
	public R<Integer> givePrint(String memberId, Integer number) {
		Member member = memberMapper.selectById(memberId);
		member.setPrintAmountGive(member.getPrintAmountGive() + number);
		return new R<>(memberMapper.updateById(member));
	}

	@GetMapping("/addGiftMembership")
	@ApiOperation("增加会员赠送次数")
	public R<Integer> addGiftMembership(String memberId, Integer number) {
		Member member = memberMapper.selectById(memberId);
		member.setGiftMembership(member.getGiftMembership() + number);
		return new R<>(memberMapper.updateById(member));
	}

	@GetMapping("/getGiftMembership")
	@ApiOperation("查询会员赠送次数")
	public R<Object> getGiftMembership(String memberId) {
		Member member = memberMapper.selectById(memberId);

		Map<String, Object> result = new HashMap<>();
		result.put( "giftMembership", member.getGiftMembership());
		return new R<>( result);
	}

	/**
	 * 增加学生当天累积练琴时长
	 *
	 * @param paramsJson 参数
	 * @return com.shycloud.mido.common.core.util.R
	 * @author xiaoxing.yu
	 * @date 2020/7/8 9:35
	 */
	@PostMapping("addAccTimeDaily")
	@ApiOperation("增加学生当天累积练琴时长")
	public R<Object> addAccumulatedPlayTimeDaily(@RequestBody String paramsJson) {
		JSONObject paramsJSONObject = JSONObject.parseObject(paramsJson);
		Integer timeSpent = paramsJSONObject.getInteger("timeSpent");
		String dateString = paramsJSONObject.getString("dateString");
		String memberId = SecurityUtils.getMember().getId();
		String studentId = getStudentId(memberId);

		//studentId为0说明学生可能还没有老师或者绑定机构，但学生依旧可以累积练琴时长，这时我们存memberId就可以了
//		if (studentId.equals("0")) return new R(CommonConstants.FAIL, "未找到学生", false);
		Boolean addResult;

		try {
			if (dateString != null) {
				new SimpleDateFormat("yyyy-MM-dd").parse(dateString);
			}
			addResult = memberService.addPlayTimeDaily(studentId,
					timeSpent, dateString, memberId);
		} catch (ParseException exception) {
			return new R<>(CommonConstants.FAIL, "日期格式有误, 请传输yyyy-MM-dd", false);
		}

		return new R<>(addResult);
	}

	/**
	 * 获取学生当天累积练琴时长
	 *
	 * @return com.shycloud.mido.common.core.util.R
	 * @author xiaoxing.yu
	 * @date 2020/7/8 9:35
	 */
	@GetMapping("getAccTimeDaily")
	@ApiOperation("获取学生当天累积练琴时长")
	public R<Object> getAccumulatedPlayTimeDaily(String dateString) {
		StudentPlayTimeDaily playTimeDaily;
		String memberId = SecurityUtils.getMember().getId();
		String studentId = getStudentId(memberId);
//		if (studentId.equals("0")) return new R(CommonConstants.FAIL, "未找到studentId", false);

		try {
			new SimpleDateFormat("yyyy-MM-dd").parse(dateString);
			playTimeDaily = memberService.getPlayTimeDaily(
					memberId, dateString);

			if (playTimeDaily == null) {
				playTimeDaily.setDate(new SimpleDateFormat("yyyy-MM-dd").parse(dateString));
				playTimeDaily.setPlayTime(0);
				playTimeDaily.setMemberId(memberId);
				playTimeDaily.setStudentId(studentId);
				return new R<>(playTimeDaily);
			}
		} catch (ParseException exception) {
			return new R<>(CommonConstants.FAIL, "日期格式有误, 请传输yyyy-MM-dd", false);
		}

		return new R<>(playTimeDaily);
	}

	/**
	 * 更新用户积分
	 *
	 * @param paramsJson 参数
	 * @return com.shycloud.mido.common.core.util.R
	 * @author xiaoxing.yu
	 * @date 2020/7/8 9:35
	 */
	@PostMapping("updateMemberPoints")
	@ApiOperation("更新用户积分")
	public R<Object> updateMemberPoints(@RequestBody String paramsJson) {
		JSONObject paramsJSONObject = JSONObject.parseObject(paramsJson);
		Integer rewardId = paramsJSONObject.getInteger("rewardId");
		String memberId = SecurityUtils.getMember().getId();

		return new R<>(memberService.updateMemberPoints(rewardId, memberId));
	}

	/**
	 * 获取用户积分
	 *
	 * @return com.shycloud.mido.common.core.util.R
	 * @author xiaoxing.yu
	 * @date 2020/7/8 9:35
	 */
	@GetMapping("getMemberPoints")
	@ApiOperation("获取用户积分")
	public R<Integer> getMemberPoints() {
		String memberId = SecurityUtils.getMember().getId();
		Member member = memberService.getById(memberId);

		return new R<>(member.getPoints());
	}

	/**
	 * 更新用户经验值
	 *
	 * @param paramsJson 参数
	 * @return com.shycloud.mido.common.core.util.R
	 * @author xiaoxing.yu
	 * @date 2020/7/8 9:35
	 */
	@PostMapping("updateMemberExp")
	@ApiOperation("更新用户经验值")
	public R<Object> updateMemberExp(@RequestBody String paramsJson) {
		JSONObject paramsJSONObject = JSONObject.parseObject(paramsJson);
		Integer rewardId = paramsJSONObject.getInteger("rewardId");
		String memberId = SecurityUtils.getMember().getId();

		return new R<>(memberService.updateMemberExp(rewardId, memberId));
	}

	/**
	 * 获取用户经验值
	 *
	 * @return com.shycloud.mido.common.core.util.R
	 * @author xiaoxing.yu
	 * @date 2020/7/8 9:35
	 */
	@GetMapping("getMemberExp")
	@ApiOperation("获取用户经验值")
	public R<Integer> getMemberExp() {
		String memberId = SecurityUtils.getMember().getId();
		Member member = memberService.getById(memberId);

		return new R<>(member.getExp());
	}

	/**
	 * 领取奖励并且返回新的积分、经验值和领取状态信息
	 *
	 * @param paramsJson 领取奖励的 json 数据串
	 * @return com.shycloud.mido.common.core.util.R
	 * @author xiaoxing.yu
	 * @date 2020/7/8 9:35
	 */
	@PostMapping("claimReward")
	@ApiOperation("领取奖励")
	public R<Object> claimReward(@RequestBody String paramsJson) {
		Map<String, Object> map;
		try {
			map = memberService.claimReward(paramsJson);
		} catch (Exception e) {
			return new R<>(CommonConstants.FAIL, "领取失败", false);
		}
		return new R<>(map);
	}

	/**
	 * 获取用户积分，经验值，领取状态
	 *
	 * @return com.shycloud.mido.common.core.util.R
	 * @author xiaoxing.yu
	 * @date 2020/7/8 9:35
	 */
	@GetMapping("getMemberClaimInfo")
	@ApiOperation("获取用户积分")
	public R<Object> getMemberClaimInfo() {
		Map<String, Object> returnMap = new HashMap<>();
		List<Integer> readyForClaim = new ArrayList<>();
		List<Integer> claimed = new ArrayList<>();
		String dateString = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

		String memberId = SecurityUtils.getMember().getId();
		Member member = memberService.getById(memberId);
		List<SmMemberPlayRewardInfo> rewardInfoList = memberService.getRewardInfo();

		StudentPlayTimeDaily playTimeDaily = memberService.getPlayTimeDaily(memberId, dateString);
		int playTime = playTimeDaily == null ? 0 : playTimeDaily.getPlayTime();

		for (SmMemberPlayRewardInfo smMemberPlayRewardInfo : rewardInfoList) {
			Integer rewardId = smMemberPlayRewardInfo.getId();
			String concatKey = dateString + memberId + "_" + rewardId;

			Object obj = redisTemplate.opsForValue().get(concatKey);
			if (obj != null) {
				claimed.add(rewardId);
			} else if (obj == null && playTime >= (smMemberPlayRewardInfo.getDuration() * 60)) {
				readyForClaim.add(rewardId);
			}
		}

		returnMap.put("playTimeToday", playTime);
		returnMap.put("readyForClaim", readyForClaim);
		returnMap.put("claimed", claimed);
		returnMap.put("points", member.getPoints());
		returnMap.put("exp", member.getExp());

		return new R<>(returnMap);
	}

	@GetMapping("isLockWx")
	public R<Boolean> isLockWx() {
		return new R<>("1".equals(lockWxService.list().get(0).getIsLock()));
	}

	/**
	 * 获取每日练琴时长对应奖励信息
	 *
	 * @return com.shycloud.mido.common.core.util.R
	 * @author xiaoxing.yu
	 * @date 2020/7/8 9:35
	 */
	@GetMapping("getRewardInfo")
	@ApiOperation("获取每日练琴时长对应奖励信息")
	public R<Object> getRewardInfo() {

		Map<String, Object> returnMap = new HashMap<>();
		List<Integer> readyForClaim = new ArrayList<>();
		List<Integer> claimed = new ArrayList<>();
		String dateString = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		String memberId = SecurityUtils.getMember().getId();
		Member member = memberService.getById(memberId);

		StudentPlayTimeDaily playTimeDaily = memberService.getPlayTimeDaily(
				memberId, dateString);
		int playTime = playTimeDaily == null ? 0 : playTimeDaily.getPlayTime();
		returnMap.put("playTimeToday", playTime);

		List<SmMemberPlayRewardInfo> rewardInfoList = memberService.getRewardInfo();
		returnMap.put("rewardInfo", rewardInfoList);

		//获取积分
		returnMap.put("points", member.getPoints());

		for (SmMemberPlayRewardInfo smMemberPlayRewardInfo : rewardInfoList) {
			Integer rewardId = smMemberPlayRewardInfo.getId();
			String concatKey = dateString + memberId + "_" + rewardId;

			Object obj = redisTemplate.opsForValue().get(concatKey);
			if (obj != null) {
				claimed.add(rewardId);
			} else if (obj == null && playTime >= (smMemberPlayRewardInfo.getDuration() * 60)) {
				readyForClaim.add(rewardId);
			}
		}

		returnMap.put("readyForClaim", readyForClaim);
		returnMap.put("claimed", claimed);

		return new R<>(returnMap);
	}

	public static int yearDateDiff(String startDate) {
		Calendar calBegin = Calendar.getInstance(); // 获取日历实例
		Calendar calEnd = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date1 = new Date();
		Date date2 = new Date();
		try {
			date1 = sdf.parse(startDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		calBegin.setTime(date1); //字符串按照指定格式转化为日期
		calEnd.setTime(date2);
		return calEnd.get(Calendar.YEAR) - calBegin.get(Calendar.YEAR);
	}

	private String getStudentId(String memberId) {
		String studentId;
		//member_id
		//根据member_id获取学生ID
		OrgStudentDetailed orgStudentDetailed = studentService
				.getOne(new QueryWrapper<OrgStudentDetailed>()
						.eq(OrgStudentDetailed.COL_MEMBER_ID, memberId)
						.and(y -> y.eq(OrgStudentDetailed.COL_DEL_FLAG,
								CommonConstants.STATUS_NORMAL)));

		if (orgStudentDetailed == null) {
			studentId = "0";
		} else {
			studentId = orgStudentDetailed.getId();
		}

		return studentId;
	}

	@GetMapping("/getMemberStatistics")
	public R<Object> getMemberStatistics() {
		Map<String, Integer> map = new HashMap<>();
		Integer memberNumber = memberMapper.getMemberNumber();
		Integer teacherNumber = memberMapper.getTeacherNumber();
		Integer studentNumber = memberMapper.getStudentNumber();
		map.put("memberNumber", memberNumber);
		map.put("teacherNumber", teacherNumber);
		map.put("studentNumber", studentNumber);
		return new R<>(map);
	}

	/**
	 * 扫码
	 *
	 * @param keywords 扫码 code
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/10/20 16:49
	 **/
	@GetMapping("scan")
	public R<SmMemberScanCodeVO> scan(String keywords) {
		return new R<>(scanCodeService.scan(keywords, SecurityUtils.getMember().getId()));
	}

	/**
	 * 初始化扫码 - 判断此 图书码是否被使用过
	 *
	 * @param code 图书码
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/10/22 15:36
	 **/
	@GetMapping("activateBookInit")
	public R<Boolean> activateBookInit(String code) {
		//初始化判断有声书码是否使用过
		Boolean isUse = auditionCodeService.activateBookInit(code);
		return new R<>(isUse, isUse ? "NB" : "二维码已被使用");
	}

	/**
	 * 激活图书
	 *
	 * @param phone 电话号
	 * @param code  激活码
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/10/22 13:11
	 **/
	@GetMapping("activateBook")
	public R<Boolean> activateBook(String phone, String captcha, String code) {
		return new R<>(auditionCodeService.activateBook(phone, captcha, code));
	}

	/**
	 * udid扫码
	 *
	 * @param udidCode udid码
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/11/7 13:52
	 **/
	@GetMapping("udidScan")
	public R<Boolean> udidScan(String udidCode) {
		UdidScan udidScan = new UdidScan();
		udidScan.setUdidCode(udidCode);
		return new R<>(udidScanService.save(udidScan));
	}

	/**
	 * 更新极光推送 regId
	 *
	 * @param memberId 会员ID
	 * @param regId    极光推送会员标识
	 */
	@GetMapping("updRegId")
	public R<Integer> updRegId(String memberId, String regId) {

		Member member = memberMapper.selectById(memberId);

		member.setClientId(regId);

		return new R<>(memberMapper.updateById(member));

	}


	@GetMapping("updImUserId")
	@ApiOperation(value = "更新imUserId", tags = "IM")
	@ApiImplicitParam(name = "imUserId", value = "用户在 IM 中的唯一标识码", paramType = "query", dataType = "String")
	public R<Integer> updImUserId(String imUserId) {

		Member member = memberMapper.selectById(SecurityUtils.getMember().getId());

		member.setImUserId(imUserId);

		return new R<>(memberMapper.updateById(member));
	}

	@GetMapping("getMemberByIm")
	@ApiOperation(value = "通过im userId 获取用户信息", tags = "IM")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "imUserId", value = "用户在 IM 中的唯一标识码", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "groupId", value = "IM 群组 ID", paramType = "query", dataType = "String")
	})
	public R<Object> getMemberByIm(String imUserId, String groupId) {

		Map<String, String> resMap = new HashMap<>();

		if (StringUtils.isNotEmpty(imUserId) && StringUtils.isEmpty(groupId)) {
			List<Member> members = memberMapper
					.selectList(new QueryWrapper<Member>().eq("im_userId", imUserId));

			if (members.size() <= 0) {
				return new R<>(CommonConstants.FAIL, "未查询到IM userId 所对应的用户");
			}

			if (members.size() != 1) {
				return new R<>(CommonConstants.FAIL, "Im userId 查询到两个用户");
			}

			resMap.put("name", members.get(0).getShowname());
			resMap.put("avatar", members.get(0).getAvatar());
			resMap.put("id", members.get(0).getImUserId());
		}

		if (StringUtils.isNotEmpty(groupId)) {

			//TODO 查询用户所在的分组
			R groupR = remoteImService.getGroupByUserId(imUserId);

			if (groupR.getCode() == 1) {
				return groupR;
			} else {

				List<Map<String, Object>> resList = (List<Map<String, Object>>) groupR.getData();

				for (Map<String, Object> map : resList) {
					if (map.get("id").equals(groupId)) {

						resMap.put("name", (String) map.get("name"));
						resMap.put("avatar", null);
						resMap.put("id", (String) map.get("id"));
						return new R(resMap);
					}
				}

			}
		}
		return new R<>(resMap);
	}

	@GetMapping("test")
	public R<Integer> test() {

		int count = 0;

		List<Member> memberNew = memberMapper.selectList(new QueryWrapper<Member>()
				.eq("is_old", "3")
				.or().eq("is_old", "0"));

		for (Member member : memberNew) {

			List<MemberActivateEntity> memberActivateEntities = memberActivateMapper
					.selectList(new QueryWrapper<MemberActivateEntity>()
							.eq("member_id", member.getId()).orderByDesc("start_time"));
			if (memberActivateEntities.size() > 0) {
				if (memberActivateEntities.stream().anyMatch(x -> x.getDuration() == 0)) {
					count++;
					continue;
				}

				if (memberActivateEntities.get(0).getStartTime()
						.plusDays(memberActivateEntities.get(0).getDuration())
						.isAfter(LocalDateTime.now())) {
					count++;
				}
			}

		}

		return new R<>(count);

	}

	@GetMapping("getTotalTimeRank")
	public Integer getTotalTimeRank(String weekId, String memberId) {
		Map<String, Object> paramMap = new HashMap<>(3);
		paramMap.put("weekId", weekId);
		paramMap.put("memberId", memberId);
		memberMapper.getTotalTimeRank(paramMap);
		return (Integer) paramMap.get("rankNum");
	}

	@ApiOperation("查询体验工具")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "memberId", value = "用户ID", paramType = "query", dataType = "string", required = true)
	})
	@GetMapping("queryTryUsed")
	public R<TryUsedShareVO> tryUsedShare(String memberId) {
		String point = "tryUsedShare";
		String client = "app";

		DateTimeFormatter dateFmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");

		TryUsedShareVO tryUsedShareVO = new TryUsedShareVO();

		// 是否是会员
		VipMemberVO vipMemberVO = vipMemberService.getVipMemberDetail(memberId);

		if (Objects.nonNull(vipMemberVO) && StringUtils.equals("1", vipMemberVO.getIsVipString())) {
			LocalDate vipOverDate = vipMemberVO.getVipOverDate();
			tryUsedShareVO.setIsVip("1");
			tryUsedShareVO.setIsTry("0");
			tryUsedShareVO.setExpireDate(dateFmt.format(vipOverDate));
		} else {
			tryUsedShareVO.setIsVip("0");
			Object val = redisTemplate.opsForValue()
					.get("tryUsedShare:" + memberId + "_" + point + "_" + client);
			if (Objects.isNull(val)) {
				tryUsedShareVO.setIsTry("0");
			} else {
				tryUsedShareVO.setIsTry("1");
				String valString = (String) val;
				tryUsedShareVO.setExpireDate(valString.split("#_#")[1]);//过期时间
			}

		}
		return new R<>(tryUsedShareVO);
	}

	@ApiOperation("分享体验工具")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "memberId", value = "用户ID", paramType = "query", dataType = "string", required = true),
			@ApiImplicitParam(name = "days", value = "送几天", paramType = "query", dataType = "string")
	})
	@GetMapping("shareTryUsed")
	public R<TryUsedShareVO> shareTryUsed(String memberId, Integer days) {
		String point = "tryUsedShare";
		String client = "app";

		DateTimeFormatter dateFmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		DateTimeFormatter dateTimeFmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

		LocalDateTime now = LocalDateTime.now();
		if (Objects.isNull(days) || days == 0) {
			days = 3;
		}
		LocalDate endDate = now.toLocalDate().plusDays(days);

		LocalDateTime endTime = endDate.atTime(0, 0, 0);
		String expireDate = dateFmt.format(endDate);
		long between = ChronoUnit.SECONDS.between(now, endTime);
		redisTemplate.opsForValue().set("tryUsedShare:" + memberId + "_" + point + "_" + client,
				dateTimeFmt.format(now) + "#_#" + expireDate, between, TimeUnit.SECONDS);

		TryUsedShareVO tryUsedShareVO = new TryUsedShareVO();
		tryUsedShareVO.setIsVip("0");
		tryUsedShareVO.setIsTry("1");
		//过期时间
		tryUsedShareVO.setExpireDate(expireDate);
		return new R<>(tryUsedShareVO);
	}

	@GetMapping("shareRegister")
	@ApiOperation("H5分享界面送VIP")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "phone   ", value = "0-系统 1-家校", paramType = "query", dataType = "String", required = true),
			@ApiImplicitParam(name = "code    ", value = "页数", paramType = "query", dataType = "int", required = true),
			@ApiImplicitParam(name = "memberId", value = "每页条数", paramType = "query", dataType = "int", required = true),
			@ApiImplicitParam(name = "pageId  ", value = "标题", paramType = "query", dataType = "String", required = true)
	})
	public R<String> shareRegister(String phone, String code, String memberId, Integer pageId) {
		return new R<>(registerService.shareRegister(phone, code, memberId, pageId));
	}

	@ApiOperation(value = "周报订阅", notes = "必填项：memberId,playYears,playTarget,subscribe,birthday")
	@PostMapping("/weekSubscribe")
	public R<Boolean> weekSubscribe(@RequestBody WeekDataMemberVO weekDataMemberVO) {

		Member member = memberMapper.selectById(weekDataMemberVO.getMemberId());
		member.setSubscribe(weekDataMemberVO.getSubscribe());
		memberMapper.updateById(member);

		List<MemberDetailInfo> memberInfos = memberDetailInfoService
				.list(new QueryWrapper<MemberDetailInfo>().eq("member_id", weekDataMemberVO.getMemberId()));

		if (memberInfos.size() == 0) {
			MemberDetailInfo memberInfo = new MemberDetailInfo();
			memberInfo.setMemberId(weekDataMemberVO.getMemberId());
			memberInfo.setCreateTime(LocalDateTime.now());
			memberInfo.setPlayTarget(weekDataMemberVO.getPlayTarget());
			memberInfo.setPlayYears(weekDataMemberVO.getPlayYears());
			memberInfo.setBirthday(weekDataMemberVO.getBirthday());
			return new R<>(memberDetailInfoService.save(memberInfo));
		} else {
			for (MemberDetailInfo memberInfo : memberInfos) {
				memberInfo.setPlayTarget(weekDataMemberVO.getPlayTarget());
				memberInfo.setPlayYears(weekDataMemberVO.getPlayYears());
				memberInfo.setBirthday(weekDataMemberVO.getBirthday());
			}
			return new R<>(memberDetailInfoService.saveOrUpdateBatch(memberInfos));
		}
	}

	@PostMapping("batchSaveMemberGold")
	public R batchSaveMemberGold(@RequestBody List<Member> members) {
		List<Member> memberAfter = new ArrayList<>();
		for (Member member : members) {
			Member member1 = memberMapper.selectById(member.getId());
			member1.setGold(member1.getGold() + member.getGold());
			memberAfter.add(member1);
		}
		return new R(memberService.updateBatchById(memberAfter));
	}

	@PostMapping("addSyMemberShow")
	@ApiOperation("记录上音社显示权限标识")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "memberId", value = "用户ID", paramType = "query", dataType = "int", required = true)
	})
	public R addSyMemberShow(@RequestBody SmMemberSyShowFlg memberSyShowFlg) {

		if (memberSyShowFlg == null && memberSyShowFlg.getMemberId() == null) {
			return new R(CommonConstants.FAIL, "memberId 参数为空", false);
		}
		//用户曲集全部置为【已显示】
		if (syShowFlgService.save(memberSyShowFlg)) {
			return musicRemoteService.updateIsShowByMemberId(memberSyShowFlg.getMemberId());
		}
		return new R(CommonConstants.FAIL, "更新权限标识失败", false);
	}

	@GetMapping("getVideoPage")
	public R getVideoPage() {

		List<SmMemberVideoPage> list = videoPageService.list();

		Map<String, Object> resMap1 = new HashMap<>(3);
		resMap1.put("title", "第一天");
		resMap1.put("date", "2021-11-01");
		resMap1.put("album", list.stream().filter(x -> "1".equals(x.getType())).collect(Collectors.toList()));

		Map<String, Object> resMap2 = new HashMap<>(3);
		resMap2.put("title", "第二天");
		resMap2.put("date", "2021-11-02");
		resMap2.put("album", list.stream().filter(x -> "2".equals(x.getType())).collect(Collectors.toList()));

		Map<String, Object> resMap3 = new HashMap<>(3);
		resMap3.put("title", "第三天");
		resMap3.put("date", "2021-11-03");
		resMap3.put("album", list.stream().filter(x -> "3".equals(x.getType())).collect(Collectors.toList()));

		List<Map<String, Object>> resList = new ArrayList<>(3);
		resList.add(resMap1);
		resList.add(resMap2);
		resList.add(resMap3);

		return new R(resList);
	}

	@PostMapping("saveVideoWatchData")
	public R saveVideoWatchData(@RequestBody Map<String, Object> reqMap) {

		//用户ID
		String memberId = (String) reqMap.get("memberId");
		//视频ID
		Integer videoId = (Integer) reqMap.get("id");
		//观看进度
		Integer progress = (Integer) reqMap.get("progress");

		SmMemberVideoWatchData watchData = new SmMemberVideoWatchData();
		watchData.setVideoId(videoId);
		watchData.setMemberId(memberId);
		watchData.setProgress(progress);

		if (watchDataService.remove(new QueryWrapper<SmMemberVideoWatchData>()
				.eq(SmMemberVideoWatchData.COL_MEMBER_ID, memberId)
				.eq(SmMemberVideoWatchData.COL_VIDEO_ID, videoId))) {
			watchDataService.save(watchData);
		}

		return new R(true);
	}

	@GetMapping("delMember")
	public R delMember(String phone, String code, String isTeacher, String teacherId, String studentId) throws IOException {

		//校验验证码
		String redisCode = (String) redisTemplate.opsForValue().get(CommonConstants.DEFAULT_CODE_KEY + "SMS@" + phone);

		if (code == null) {
			return new R(CommonConstants.FAIL, "验证码已过期", false);
		}

		if (!code.equals(redisCode)) {
			return new R(CommonConstants.FAIL, "验证码不正确", false);
		}

		//获取确认时间，如果结束时间在今天之前，则可以删除，否则提示不在时间范围内，无法注销
		String endTimeM = (String) redisTemplate.opsForValue().get("delMember_" + SecurityUtils.getMember().getId() + "_endTime");

		LocalDateTime endTime = LocalDateTime.ofEpochSecond(Long.valueOf(endTimeM) / 1000, 0, ZoneOffset.ofHours(8));

		if (endTime.isAfter(LocalDateTime.now())) {
			return new R(CommonConstants.FAIL, "未到时间，暂时无法删除", false);
		}

		appleUserLogOut(SecurityUtils.getMember().getId());

		return new R(memberService.delMember(phone, isTeacher, teacherId, studentId));
	}

	/**
	 * 注销账号 x天 反悔期
	 *
	 * @param memberId 用户 ID
	 * @param dayCount 返回天数
	 * @return
	 * @author nianhua.jiang
	 * @date 2021/12/9 13:47
	 */
	@GetMapping("saveDelMemberLog")
	public R saveDelMemberLog(String memberId, Integer dayCount) {
		return new R(memberService.saveDelMemberLog(memberId, dayCount));
	}

	@GetMapping("cancelDelMemberLog")
	public R cancelDelMemberLog(String memberId) {
		redisTemplate.delete("delMember_" + memberId + "_startTime");
		redisTemplate.delete("delMember_" + memberId + "_endTime");
		return new R(true);
	}

	/**
	 * 获取账号  反悔期 时间 / 结束
	 *
	 * @param memberId 用户 ID
	 * @return
	 * @author nianhua.jiang
	 * @date 2021/12/9 13:47
	 */
	@GetMapping("getDelMemberLog")
	public R getDelMemberLog(String memberId) {

		String startTime = (String) redisTemplate.opsForValue().get("delMember_" + memberId + "_startTime");

		String endTime = (String) redisTemplate.opsForValue().get("delMember_" + memberId + "_endTime");

		Map<String, String> resMap = new HashMap<>(2);

		resMap.put("startTime", startTime);

		resMap.put("endTime", endTime);

		return new R(resMap);

	}

	@GetMapping("/logoutAppBefore")
	public R logoutAppBefore() {
		return new R(true);
	}

	@PostMapping("giveGoldByScanSyOldCode")
	public R giveGoldByScanSyOldCode(@RequestBody SmMemberScanSyOldCodeLog log) {
		log.setCreateTime(LocalDateTime.now());
		if (scanSyOldCodeLogService.count(new QueryWrapper<SmMemberScanSyOldCodeLog>()
				.eq("member_id", log.getMemberId())
				.eq("code", log.getCode())) > 0) {
			return new R(CommonConstants.FAIL, "您已经扫过此码", false);
		}
		if (scanSyOldCodeLogService.save(log)) {
			//送快乐贝
			Member member = memberService.getById(log.getMemberId());
			member.setGold(member.getGold() + 30);
			memberService.updateById(member);
		}
		return new R(true);
	}

	private Boolean appleUserLogOut(String memberId) throws IOException {

		Member member = memberService.getById(memberId);

		if (member != null && StringUtils.isEmpty(member.getAppleToken())) {
			return false;
		} else {

			AppleClient appleClient = appleClientService.getById(1);

			//请求参数
			HttpClient httpclient = HttpClientBuilder.create().useSystemProperties().build();
			HttpPost httpPost = new HttpPost("https://appleid.apple.com/auth/revoke?client_id=" + appleClient.getClientId() +
					"&client_secret=" + appleClient.getClientSecret() +
					"&token=" + member.getAppleToken() +
					"&token_type_hint=" + appleClient.getTokenTypeHint());

			httpPost.setHeader("content-type", "application/x-www-form-urlencoded");
			httpPost.setHeader("Accept", "*/*");
			httpPost.setHeader("Connection", "keep-alive");

			HttpResponse response = httpclient.execute(httpPost);
			int code = response.getStatusLine().getStatusCode();

			if (code == 200) {
				System.out.println("苹果注销成功");
				return true;
			} else {
				System.out.println("苹果注销失败");
				return false;
			}
		}
	}

//	@SneakyThrows
//	@GetMapping("batchVideo")
//	public R batchVideo() {
//
//		BufferedReader in = null;
//
//		List<SmMemberVideoPage> list = videoPageService.list();
//
//		for (SmMemberVideoPage videoPage : list) {
//
//			//请求参数
//			HttpClient httpclient = HttpClientBuilder.create().useSystemProperties().build();
//			HttpGet httpGet = new HttpGet(videoPage.getVideo() + "?avinfo");
//			HttpResponse response = httpclient.execute(httpGet);
//			int code = response.getStatusLine().getStatusCode();
//
//			if (code == 200) {
//				in = new BufferedReader(new InputStreamReader(response.getEntity()
//						.getContent(), "utf-8"));
//				StringBuffer sb = new StringBuffer("");
//				String line = "";
//				String NL = System.getProperty("line.separator");
//				while ((line = in.readLine()) != null) {
//					sb.append(line + NL);
//				}
//				in.close();
//				String resStr = sb.toString();
//				JSONObject jsonObject = JSONObject.parseObject(resStr);
//				JSONObject jsonObjectF = jsonObject.getJSONObject("format");
//				String duration = jsonObjectF.getString("duration");
//				videoPage.setTime(duration);
//			}
//			videoPageService.updateBatchById(list);
//		}
//		return new R();
//	}

}
